package com.example.springaopstudy.config;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

//表示是一个切面，要使用aop进行方法增强
@Aspect
//一定要注册到容器中
@Component
public class AopAspect {

    //切点：定义要增强的方法匹配规则
    @Pointcut("execution(* com.example..service.*Service.query(..))")
    public void suibian(){}

    @Around("suibian()")
    public Object around(ProceedingJoinPoint joinPoint){
        try {
            //统计方法的执行时间：前后时间相减
            long start = System.currentTimeMillis();
            //这个方法，就是@Pointcut匹配到的方法，执行
            Object obj = joinPoint.proceed();
            long end = System.currentTimeMillis();
            System.out.println("========================");
            System.out.println("执行时间："+(end-start)+"毫秒");
            return obj;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    //添加其他的通知
    @Before("suibian()")
    public void bef(){
        System.out.println("===================@Before");
    }

    @After("suibian()")
    public void aft(){
        System.out.println("===================@After");
    }

    @AfterReturning("suibian()")
    public void afterRet(){
        System.out.println("===================@AfterReturning");
    }

    @AfterThrowing("suibian()")
    public void afterThr(){
        System.out.println("===================@AfterThrowing");
    }
}
